#include "camerapage.h"
#include <QPainterPath>
#include "camera/globalinstance.h"

CameraPage::CameraPage(QWidget *parent, QRect recordingRect)  :
    QStackedWidget(parent),
    m_recordingRect(recordingRect)
{
    //初始化
    initLayout();
    devicePull = new DevicePull();
    initConnect();

    //获取显示摄像头
    CurrentDeviceInfo::current_device_list.clear();
    CurrentDeviceInfo::current_device_list = QCameraInfo::availableCameras();
    QString devname;
    if(!CurrentDeviceInfo::current_device_list.empty()){
        int index = ConfigHandler().getCurrentCamera();
        if(0 <= index < CurrentDeviceInfo::current_device_list.count()){
            devname = CurrentDeviceInfo::current_device_list.at(index).deviceName();
            creatCameraPage(devname.toLocal8Bit().data());
        }else{
            devname = CurrentDeviceInfo::current_device_list.at(0).deviceName();
            creatCameraPage(devname.toLocal8Bit().data());
        }



    }
    else{
        displayCameraError(1);
    }

    //调整大小
    m_animation = new QPropertyAnimation(this, "geometry", this);
    m_animation->setEasingCurve(QEasingCurve::InOutQuad);
    m_animation->setDuration(160);
    connect(m_animation, &QPropertyAnimation::finished,
            this, &CameraPage::animationEnded);

    setAttribute(Qt::WA_TransparentForMouseEvents);
    int sideVal = 36;
    int handleSide = sideVal / 4;
    const QRect areaRect(0, 0, sideVal, sideVal);
    const QRect handleRect(0, 0, handleSide, handleSide);
    m_TLHandle = m_TRHandle = m_BLHandle = m_BRHandle
               = m_LHandle = m_THandle = m_RHandle = m_BHandle = handleRect;
    m_TLArea = m_TRArea = m_BLArea = m_BRArea = areaRect;

    m_areaOffset = QPoint(-sideVal/2, -sideVal/2);
    m_handleOffset = QPoint(-handleSide/2+1, -handleSide/2+1);
}

void CameraPage::creatCameraPage(const char *in_devname)
{
    //1. 新建一个摄像头的对象
    if(camera == nullptr){
        camera = new KylinCamera();
        camera->camera_log_init(LOG_NOTICE);
    }

    KylinCameraInfo camera_info = cameraInfoSet(in_devname, scale);//默认选取最高分辨率，所以第二个参数为0
    if(!(CurrentDeviceInfo::available_format == V4L2_PIX_FMT_MJPEG ||
        CurrentDeviceInfo::available_format == V4L2_PIX_FMT_YUYV)){
        has_device = true;
        return;
    }
    //2. 初始化摄像头设备，初始化镜像、捕捉画面的显示
    if(videoDisplay){
        hasLayout->removeWidget(videoDisplay);
        delete videoDisplay;
        videoDisplay = nullptr;
    }
    videoDisplay = camera->create(haveDevicePage, &camera_info);
    //避免设备被占用时发生崩溃
    if(videoDisplay != nullptr){
        camera->camera_display_mirror(1);   //镜像设置后为正常显示
    }
    m_pGraphicsOpacityEffect1 = new QGraphicsOpacityEffect(this);
    //设备被占用返回值NULL
    if(videoDisplay == NULL){
        QString warning = tr("The camera is occupied, please check the use of the device!");
        ScreencapSaver().sendMessage(warning);
        camera = nullptr;
        m_pGraphicsOpacityEffect1 = nullptr;
        swithToNoDevicePage(1);
        return ;
    }
    camera->camera_set_background(QColor("#232426"));
    has_device = true;
    //videoDisplay 页面设置
    connect(videoDisplay,SIGNAL(readout()),this,SLOT(pullOut()));//打开设备后，开启监听设备中断连接的信号
    videoDisplay->show();
    hasLayout->addWidget(videoDisplay);
    if(videoDisplay){
        updateDisplayMask();
    }

    //5. 切换到有设备的页面
    Q_EMIT swithToHasDevicePage();
}

void CameraPage::initLayout()
{
    //背景
    setAttribute(Qt::WA_TranslucentBackground);
    haveDevicesInit();
    noDevicesInit();

    this->addWidget(haveDevicePage);
    this->addWidget(noDevicePage);

    this->setMinimumSize(CAMERA_MIN_SIZE);
    this->setMaximumSize(CAMERA_MAX_SIZE);
    this->resize(CAMERA_DEFAULT_SIZE);
    this->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

    this->hide();

    this->setWindowFlags( Qt::WindowStaysOnTopHint
                          | Qt::FramelessWindowHint
                          | Qt::Tool );
    if(!m_recordingRect.isEmpty()){
        noDevicePage->setMouseTracking(true);
    }
    setProperty("useStyleWindowManager", false); //覆盖主题的标题栏设置
    initFontSize();
}
void CameraPage::haveDevicesInit()
{
    //有设备界面
    haveDevicePage = new QWidget(this);
    this->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
//    haveDevicePage->setStyleSheet( QString("QWidget{border: none;"
//                                 "background:none;"
//                                 "border-radius:%1px;}"
//                                 "" ).arg(CAMERA_RADIUS));
    hasLayout = new QStackedLayout(haveDevicePage);
    hasLayout->setStackingMode(QStackedLayout::StackAll);
}

void CameraPage::noDevicesInit()
{
    noDevicePage = new QWidget(this);
    QVBoxLayout * noDeviceLayout = new QVBoxLayout(noDevicePage);
    noDevicePage->setStyleSheet( QString( "QWidget{border:none; "
                                "background: rgba(39, 39, 39, 0.85);"
                                "border-radius: %1px;}"
                                 ).arg(CAMERA_RADIUS));
    QWidget * noDevice = new QWidget(noDevicePage);
    noDevice->setStyleSheet( QString ("QWidget{border:none; "
                                "background:none ;" //注释颜色会加深
                                "border-radius:%1px;}"
                                 ).arg(CAMERA_RADIUS));
    QVBoxLayout * layout = new QVBoxLayout(noDevice);
    labelIcon = new QLabel(noDevice) ;
    labelIcon->setFixedSize(QSize(64,64));
    QPixmap noCameraPix(":/icon/no_camera.svg");
    labelIcon->setPixmap(noCameraPix);
    labelIcon->setStyleSheet("QLabel{border:none; "
                                "background: transparent;"
                                "border-radius:5px}");
    labelText = new QLabel(noDevice) ;
    labelText->setText(tr("The camera device was not detected"));
    labelText->setStyleSheet("QLabel { color: white; }");
    layout->addWidget(labelIcon,0,Qt::AlignCenter);
    layout->addWidget(labelText,0,Qt::AlignCenter);
    layout->setContentsMargins(0,0,0,0);

    noDeviceLayout->addWidget(noDevice,0,Qt::AlignCenter);
}

void CameraPage::initConnect()
{
    connect(this,&CameraPage::swithToHasDevicePage,this,&CameraPage::displayCamera);
    connect(this,&CameraPage::swithToNoDevicePage,this,&CameraPage::displayCameraError);
    //设备拔插
    connect(devicePull,&DevicePull::creatCameraPageSig,this,&CameraPage::creatCameraPage);  //插入摄像头后创建摄像头
    connect(devicePull,&DevicePull::change_deviceSig,this,&CameraPage::creatCameraPage);    //拔出摄像头后创建摄像头
    connect(GlobalInstance::getInstance(),&GlobalInstance::displayCameraErrorSig,this,&CameraPage::displayCameraError);  //拔出并且当前无设备
    connect(devicePull,&DevicePull::device_pull_out,this,&CameraPage::exception_handing);   //拔出摄像头处理
    connect(this,&CameraPage::lockSigForDevicePull,devicePull,&DevicePull::systemLock);
    //设备选择
    connect(GlobalInstance::getInstance(),&GlobalInstance::sigSelectCameraFromList,this,&CameraPage::cameraChanged);
}

KylinCameraInfo CameraPage::cameraInfoSet(const char *in_devname, QString scale)
{
    //1. 重置设备信息,设备名需要更新
    CurrentDeviceInfo::available_size.clear();
    //2. 根据设备名，读取该设备的一些可用的设置信息
    V4l2DeviceInfo device_info;
    memset(&device_info,0X00,sizeof(V4l2DeviceInfo));
    memcpy(device_info.dev_path, in_devname, strlen(in_devname)+1);
    camera->enum_device(&device_info);//获取包含设备信息的一个结构体
    //2.1 获取设备支持的编码格式，并根据优先级设置好要使用的编码格式
    CurrentDeviceInfo::available_format = 0;
    CurrentDeviceInfo::formatFlag = 0;
    for(int i=0;i<10;i++){
      TypePixFormats *pixfmt = &device_info.fmt_supported[i];
      unsigned int format = pixfmt->fmt.pixelformat;
      char formatArray[] = { (char)(format&0xff), (char)((format>>8)&0xff),(char)((format>>16)&0xff), (char)((format>>24)&0xff), 0 };
      qDebug() << "***pixel format: " << formatArray;
      if( strcmp(formatArray,"MJPG") == 0 ) {
          CurrentDeviceInfo::formatFlag = i;
          CurrentDeviceInfo::available_format = V4L2_PIX_FMT_MJPEG;
          break;
      }else if( strcmp(formatArray,"YUYV") == 0 ) {
          CurrentDeviceInfo::formatFlag = i;
          CurrentDeviceInfo::available_format = V4L2_PIX_FMT_YUYV;
      }else{
          qDebug() << "unsupported format: " << formatArray;
      }
    }
    if(!(CurrentDeviceInfo::available_format == V4L2_PIX_FMT_YUYV ||
            CurrentDeviceInfo::available_format == V4L2_PIX_FMT_MJPEG)){//该摄像头不支持MJPG/YUYV编码，设置为默认编码
        qDebug()<<"切换到无摄像头画面";
        displayCameraError(2);
    }
    qDebug() << "showMegFormat" << CurrentDeviceInfo::available_format;
    //2.2 获取设备支持的分辨率，以及各分辨率下支持的最大帧率
    int scaleCount = 0;
    TypePixFormats fmt = device_info.fmt_supported[CurrentDeviceInfo::formatFlag];
    for(int j = 0; j < 50; j++) {
        TypeFramesizes *fsize = &fmt.frm_sizes[j];
        if(fsize->frm_size.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
            QPair<uint,uint> discrete;
            discrete.first = fsize->frm_size.discrete.width;
            discrete.second = fsize->frm_size.discrete.height;

            sizeAndfps cell;

            if(discrete.first != 0){
                cell.available_size = discrete;
                cell.fps = fsize->frm_ivals[0].discrete.denominator;
                CurrentDeviceInfo::available_size.push_back(cell);
                qDebug() << "showMeg" << cell.available_size.first << cell.available_size.second << cell.fps;
                scaleCount++;
            }else{
                continue;
            }
        }
    }
    qDebug()<<"count of resolution pairs:"<<scaleCount;
    //3. 对读到的分辨率排序以及设置默认分辨率选项
    CurrentDeviceInfo::sort_resolution();
    int scale_num = 0;//默认取第一项分辨率
    //3.1 判断gsettings中保存的分辨率是否在当前摄像头中存在
    QStringList Scales;
    unsigned int Scale_width, Scale_height;
    if(scale != ""){
        Scales = scale.split("*");
        Scale_width = Scales.at(0).toUInt();
        Scale_height = Scales.at(1).toUInt();
        for(int i = 0; i < CurrentDeviceInfo::available_size.length(); i++){
            if(CurrentDeviceInfo::available_size[i].available_size.first == Scale_width && CurrentDeviceInfo::available_size[i].available_size.second == Scale_height){
                scale_num = i;
                break;
            }
        }
    }
    m_width = CurrentDeviceInfo::available_size[scale_num].available_size.first;
    m_height = CurrentDeviceInfo::available_size[scale_num].available_size.second;
    scale = QString::number(m_width) + "*" + QString::number(m_height);
//    gsettingItem->setScaleIndex(scale_num);
//    gsettingItem->setScale(CurrentDeviceInfo::available_size[scale_num].available_size.first, CurrentDeviceInfo::available_size[scale_num].available_size.second);

    //4. 初始化设备信息（具体的，当前使用的参数）
    //4.1 设备名
    KylinCameraInfo camera_info;
    memset(&camera_info,0X00,sizeof(KylinCameraInfo));
    memcpy(camera_info.devname, in_devname, strlen(in_devname)+1);
    strcpy(CurrentDeviceInfo::current_indevice,in_devname);
    QString archName = QSysInfo::currentCpuArchitecture();
    qDebug() << "archName: " << archName;
    //4.2 编码格式
    camera_info.format = CurrentDeviceInfo::available_format;
    //4.3 分辨率
    camera_info.width = CurrentDeviceInfo::available_size[scale_num].available_size.first;
    camera_info.height = CurrentDeviceInfo::available_size[scale_num].available_size.second;
    CurrentDeviceInfo::current_size.available_size.first = camera_info.width;
    CurrentDeviceInfo::current_size.available_size.second = camera_info.height;
    //4.4 帧率
    camera_info.fps = CurrentDeviceInfo::available_size[scale_num].fps;
    CurrentDeviceInfo::current_size.fps = camera_info.fps;

    qDebug() << "showMeg" << camera_info.format;
    qDebug() << "showMeg" << camera_info.width << "*" <<camera_info.height << "*" << camera_info.fps;

    m_camInfo = camera_info;

    return camera_info;
}

void CameraPage::pullOut()
{
}

void CameraPage::change_device(const char *in_device)
{
    //1. 创建探测设备是否可用的kylinCamera类
    // cameraTmp = new KylinCamera;
    // cameraTmp->camera_log_init(LOG_NOTICE);
    bool res = cameraInfoSetTmp(in_device);
    //设备被占用返回值NULL
    if(!res){
        //切换失败的提示
        QString warning = tr("The camera is occupied or there is an exception in the target switching device, please check the device!");
        ScreencapSaver().sendMessage(warning);
    }else{
        //delete cameraTmp;
        //cameraTmp = nullptr;
        stopCamera();
        creatCameraPage(in_device);
        return;
        uint formatBefore = CurrentDeviceInfo::available_format;
        //设备可用，丢弃上个设备的使用信息，切换选中的设备，并更改为默认状态
        KylinCameraInfo camera_infox = cameraInfoSet(in_device, scale);

        if(CurrentDeviceInfo::available_format != V4L2_PIX_FMT_YUYV &&
                CurrentDeviceInfo::available_format != V4L2_PIX_FMT_MJPEG){
            stopCamera();
            Q_EMIT swithToNoDevicePage(2);
        }else{
            QString tips = tr("camera is being used by kylin-camera");
            ScreencapSaver().sendMessage(tips);
            if(formatBefore == V4L2_PIX_FMT_MJPEG || formatBefore == V4L2_PIX_FMT_YUYV){
                camera->camera_set_param(&camera_infox);
            }else{
                startExistCamera(camera_infox);
                return;
            }
            Q_EMIT swithToHasDevicePage();
        }
        return;
    }
}

bool CameraPage::cameraInfoSetTmp(const char *in_devname)
{
    //1. 根据设备名，读取该设备的一些设置信息
    V4l2DeviceInfo device_info;
    memset(&device_info,0X00,sizeof(V4l2DeviceInfo));
    memcpy(device_info.dev_path, in_devname, strlen(in_devname)+1);
    camera->enum_device(&device_info);//获取包含设备信息的一个结构体
    //2. 读取kylinCamera的几项基本信息：设备名、编码格式、分辨率、帧率
    KylinCameraInfo camera_info;
    //2.1 获取并设置设备名
    memset(&camera_info,0X00,sizeof(KylinCameraInfo));
    memcpy(camera_info.devname, in_devname, strlen(in_devname)+1);

    uint available_formatTmp = 0;
    int formatFlagTmp = 0;
    for(int i=0;i<10;i++){
      TypePixFormats *pixfmt = &device_info.fmt_supported[i];
      unsigned int format = pixfmt->fmt.pixelformat;
      char formatArray[] = { (char)(format&0xff), (char)((format>>8)&0xff),(char)((format>>16)&0xff), (char)((format>>24)&0xff), 0 };
      qDebug() << "***pixel format: " << formatArray;
      if( strcmp(formatArray,"MJPG") == 0 ) {
          formatFlagTmp = i;
          available_formatTmp = V4L2_PIX_FMT_MJPEG;
          break;
      }else if( strcmp(formatArray,"YUYV") == 0 ) {
          formatFlagTmp = i;
          available_formatTmp = V4L2_PIX_FMT_YUYV;
      }else{
          qDebug() << "unsupported format: " << formatArray;
      }
    }
    if(available_formatTmp == 0){//该摄像头不支持MJPG/YUYV编码，设置为默认编码
        available_formatTmp = device_info.fmt_supported[0].fmt.pixelformat;
    }
    camera_info.format = available_formatTmp;
    //2.2 获取设备支持的分辨率，以及各分辨率下支持的最大帧率
    TypePixFormats fmt = device_info.fmt_supported[formatFlagTmp];
    for(int j = 0; j < 50; j++) {
        TypeFramesizes *fsize = &fmt.frm_sizes[j];
        if(fsize->frm_size.type == V4L2_FRMSIZE_TYPE_DISCRETE) {
            QPair<uint,uint> discrete;
            discrete.first = fsize->frm_size.discrete.width;
            discrete.second = fsize->frm_size.discrete.height;
            if(discrete.first != 0){
                camera_info.width = discrete.first;
                camera_info.height = discrete.second;
                camera_info.fps = fsize->frm_ivals[0].discrete.denominator;
                break;
            }else{
                continue;
            }
        }
    }
    bool res = camera_info.devname && camera_info.format &&camera_info.fps && camera_info.width;
    return res;
}

void CameraPage::cameraChanged(QString DeviceNamePath)
{
    qDebug()<<"更新摄像头显示 cameraChanged";

    char *in_device = DeviceNamePath.toLocal8Bit().data();
    V4l2DeviceInfo device_info;
    memset(&device_info,0X00,sizeof(V4l2DeviceInfo));
    memcpy(device_info.dev_path, in_device, strlen(in_device)+1);
    if(camera){
        camera->enum_device(&device_info);
    }

    //切换设备
    if( CurrentDeviceInfo::current_indevice != DeviceNamePath){
        cameraInfoSet(DeviceNamePath.toLocal8Bit().data(), "");
        change_device(DeviceNamePath.toLocal8Bit().data());
    }
}

void CameraPage::exception_handing()
{
    if (videoDisplay) {
        hasLayout->removeWidget(videoDisplay);
        videoDisplay->deleteLater();
        videoDisplay = nullptr;
    }
}

void CameraPage::startExistCamera(KylinCameraInfo cameraInfo)
{
    if(camera == nullptr){
        camera = new KylinCamera;
        camera->camera_log_init(LOG_NOTICE);
    }
    videoDisplay = camera->create(this, &cameraInfo);
    //设备被占用返回值NULL
    if(videoDisplay == NULL){
        QString warning = tr("The camera is occupied, please check the use of the device!");
        ScreencapSaver().sendMessage(warning);
        delete camera;
        camera = nullptr;
        return;
    }

    camera->camera_set_background(QColor("#232426"));
    QString tips = tr("camera is being used by kylin-camera");
    ScreencapSaver().sendMessage(tips);
    m_pGraphicsOpacityEffect1 = new QGraphicsOpacityEffect(this);
    //设备被占用返回值NULL

    connect(videoDisplay,SIGNAL(readout()),this,SLOT(pullOut()));

    camera->camera_display_mirror(true);

    qDebug() << "cache : " << videoDisplay->children();
    hasLayout->addWidget(videoDisplay);
}

void CameraPage::displayCamera()
{
    this->setCurrentWidget(haveDevicePage);
    this->show();
}

void CameraPage::displayCameraError(int code)
{
/* code == 1 No device were found
 * code == 2 not support current device
 */
    this->setCurrentWidget(noDevicePage);
    this->show();
}

void CameraPage::initFontSize()
{
    //只有非标准字号的控件才需要绑定
    connect(this, &CameraPage::setFontSizeSignal, this, &CameraPage::lable2SetFontSizeSlot);
    connect(kdk::kabase::Gsettings::getPoint(), &kdk::kabase::Gsettings::systemFontSizeChange, this, [=]() {
        //获取字号的值
        int fontSizeKey = kdk::kabase::Gsettings::getSystemFontSize().toInt();
        //发送改变信号
        qDebug()<<"** 系统字体改变";
        if (fontSizeKey > 0) {
            if (fontSizeKey > 15) {
                fontSizeKey = 15;
            }
            Q_EMIT setFontSizeSignal(fontSizeKey);
        }
    });
    //启动时设置字号
    int fontSizeKey = 11; //系统默认字号
    int fontSizeKeyTmp = kdk::kabase::Gsettings::getSystemFontSize().toInt();
    if (fontSizeKeyTmp > 0) {
        fontSizeKey = fontSizeKeyTmp;
    }
    if (fontSizeKey > 15) {
        fontSizeKey = 15;
    }
    Q_EMIT setFontSizeSignal(fontSizeKey);
}

void CameraPage::lable2SetFontSizeSlot(int size)
{
    //默认大小12px,换算成pt为9
    double lable2BaseFontSize = DEFAULT_FONT_SIZE;
    double nowFontSize = lable2BaseFontSize * double(size) / DEFAULT_FONT_SIZE; // 11为系统默认大小
    QFont font;
    font.setPointSizeF(nowFontSize);
    if(labelText){
        labelText->setFont(font);
    }
}

void CameraPage::stopCamera()
{
    this->show(); //关闭的时候会发生错误
    if(camera != nullptr || CurrentDeviceInfo::available_format == V4L2_PIX_FMT_MJPEG || CurrentDeviceInfo::available_format == V4L2_PIX_FMT_YUYV)
    {
        if(videoDisplay){
            delete videoDisplay;
            videoDisplay = nullptr;
        }
        delete camera;
        camera = nullptr;
        m_pGraphicsOpacityEffect1 = nullptr;
    }
}

void CameraPage::updateDisplayMask()
{
    //设置容器圆角蒙版
    if(videoDisplay){
        QPainterPath path;
        path.addRoundedRect(this->rect(), 10, 10);
        QPixmap pixmap(this->size());
        pixmap.fill(Qt::transparent); // 使用透明背景
        QPainter painter(&pixmap);
        painter.setRenderHint(QPainter::Antialiasing, true); // 启用抗锯齿
        painter.setRenderHint(QPainter::HighQualityAntialiasing, true); // 启用高质量抗锯齿
        painter.setBrush(Qt::black);
        painter.setPen(Qt::NoPen);
        painter.drawPath(path);

        this->setMask(pixmap.mask());
    }
}

CameraPage::SideType CameraPage::getMouseSide(const QPoint &point) const
{
    if (m_TLArea.contains(point)) {
        return TOPLEFT_SIDE;
    }
    else if (m_TRArea.contains(point) ) {
        return TOPRIGHT_SIDE;
    } else if (m_BLArea.contains(point)) {
        return BOTTONLEFT_SIDE;
    } else if (m_BRArea.contains(point)) {
        return BOTTONRIGHT_SIDE;
    } else if (m_LArea.contains(point)) {
        return LEFT_SIDE;
    } else if (m_TArea.contains(point)) {
        return TOP_SIDE;
    } else if (m_RArea.contains(point)) {
        return RIGHT_SIDE;
    } else if (m_BArea.contains(point)) {
        return BOTTON_SIDE;
    } else {
        return NO_SIDE;
    }
}

bool CameraPage::getCameraWidChanged()
{
    return m_cameraChanged;
}

void CameraPage::setCameraWidChanged(bool ischanged)
{
    m_cameraChanged = ischanged;
}

void CameraPage::saveGeometry()
{
    m_geometryBackup = geometry();
}

QRect CameraPage::savedGeometry()
{
    return m_geometryBackup;
}

void CameraPage::UpdateResolution(V4l2DeviceInfo *device)
{
    if(camera){
        camera->enum_device(device);
    }
}

void CameraPage::resizeEvent(QResizeEvent *e)
{
    m_cameraChanged =true;
    updateAreas();
    if(videoDisplay){
        videoDisplay->resize(this->size());
    }
    updateDisplayMask();

}

void CameraPage::moveEvent(QMoveEvent *e)
{
    updateAreas();
    updateDisplayMask();
}

void CameraPage::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == Qt::RightButton) {
        return;
    }

    if (e->button() == Qt::LeftButton) {
        isMousePress = true;
        m_dragStartPoint_g = e->globalPos();

        if (m_recordingRect.contains(e->globalPos())) {
            if (this->geometry().contains(e->globalPos())){
                isMoveCamera = true;
            }
        }

        this->saveGeometry();
        isMouseRelease = false;
    }

//    updateCursor();
}

void CameraPage::mouseMoveEvent(QMouseEvent *e)
{
    if(isMousePress){
        if(isMoveCamera){
            updateCameraPos(e->globalPos());
        }

    }else{
//        m_mouseOverHandleCamera = getMouseSide(e->globalPos());
//        qDebug()<<"更新区域 m_mouseOverHandle"<<m_mouseOverHandleCamera;
//        updateCursor();
    }
}

void CameraPage::mouseReleaseEvent(QMouseEvent *e)
{
    if (Qt::LeftButton == e->button()) {
        if(this->getCameraWidChanged()){
            this->setCameraWidChanged(false);
        }
        update();

        isMoveCamera = false;
        isSizeCamera = false;
        isMousePress = false;
        isMouseRelease = true;
//        updateCursor();
    }
}

void CameraPage::updateAreas()
{
    QRect r = rect();
    m_TLArea.moveTo(m_areaOffset + pos());
    m_TRArea.moveTo(r.topRight() + m_areaOffset + pos());
    m_BLArea.moveTo(r.bottomLeft() + m_areaOffset + pos());
    m_BRArea.moveTo(r.bottomRight() + m_areaOffset + pos());

    m_LArea = QRect(m_TLArea.bottomLeft(), m_BLArea.topRight());
    m_TArea = QRect(m_TLArea.topRight(), m_TRArea.bottomLeft());
    m_RArea = QRect(m_TRArea.bottomLeft(), m_BRArea.topRight());
    m_BArea = QRect(m_BLArea.topRight(), m_BRArea.bottomLeft());

    m_TLHandle.moveTo(m_TLArea.center() + m_handleOffset);
    m_BLHandle.moveTo(m_BLArea.center() + m_handleOffset);
    m_TRHandle.moveTo(m_TRArea.center() + m_handleOffset);
    m_BRHandle.moveTo(m_BRArea.center() + m_handleOffset);
    m_LHandle.moveTo(m_LArea.center() + m_handleOffset);
    m_THandle.moveTo(m_TArea.center() + m_handleOffset);
    m_RHandle.moveTo(m_RArea.center() + m_handleOffset);
    m_BHandle.moveTo(m_BArea.center() + m_handleOffset);
}

void CameraPage::updateCameraPos(QPoint point)
{
    QRect initialRect = this->savedGeometry().normalized();
    QPoint newTopLeft = initialRect.topLeft() + (point- m_dragStartPoint_g);
    QRect finalRect(newTopLeft, initialRect.size());

    if (finalRect.left() < m_recordingRect.left()) {
        finalRect.setLeft(m_recordingRect.left());
    } else if (finalRect.right() > m_recordingRect.right()) {
        finalRect.setLeft(m_recordingRect.right() - this->width());
    }
    if (finalRect.top() < m_recordingRect.top()) {
        finalRect.setTop(m_recordingRect.top());
    } else if (finalRect.bottom() > m_recordingRect.bottom()) {
        finalRect.setBottom(m_recordingRect.bottom());
        finalRect.setTop(m_recordingRect.bottom() - this->height());
    }
    QRect newRect = finalRect.normalized().intersected(m_recordingRect);

    if(!m_recordingRect.contains(newRect.bottomRight())){
        newRect.setBottomRight(m_recordingRect.bottomRight());
    }
    this->move(newRect.topLeft());
    update();
}
